package thread;

import java.util.concurrent.*;

public class ThreadWork1 {

    private static final int threads = 100;
    private CountDownLatch countDownLatch = new CountDownLatch(threads);

    public static void main1(String[] args) {
        // 使用 newFixedThreadPool 来创建线程池 - 指定个数是 100
        ExecutorService fixedPool = Executors.newFixedThreadPool(10);
        // 注册 100 个任务
        for (int i = 0; i < 100; i++) {
            // 这 100 个任务由这10个线程分配
            int num = i;
            fixedPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("酒國最牛" + num);
                }
            });
        }
    }

    public static void main2(String[] args) {
        // 使用 newCachedThreadPool 来创建线程池
        ExecutorService cachedPool = Executors.newCachedThreadPool(); // 线程的数量数动态的
        // 注册 10 个任务
        for (int i = 0; i < 10; i++) {
            int num = i;
            cachedPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "," + num);
                }
            });
        }
    }

    public static void main3(String[] args) {
        // 使用 newSingleThreadExecutor 创建线程池
        ExecutorService singlePool = Executors.newSingleThreadExecutor(); // 这里只有一个线程
        for (int i = 0; i < 10; i++) {
            int num = i;
            singlePool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + "," + num);
                }
            });
        }
    }

    // 打印线程信息
    private void printThreadInfor() {
        try {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(50);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) {
        // 使用 newScheduledThreadPool 来创建线程池
        ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(3);
        scheduledPool.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "延迟1秒后运行...");
            }
        },1, TimeUnit.SECONDS);
    }

}
